﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OF.Controls
{
    [DefaultProperty("Text"), ToolboxData("<{0}:OFGridView runat=server></{0}:OFGridView>")]
    public class OFGridView:System.Web.UI.WebControls.GridView
    {
        public OFGridView():base()
        {
            this.CssClass = "gridScroller";
            this.ShowHeader = true;
            this.AutoGenerateColumns = false;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.UseAccessibleHeader = true;                                //使用<th>替换<td> 
            this.HeaderRow.TableSection = TableRowSection.TableHeader;      //HeaderRow将被<thead>包裹，数据行将被<tbody>包裹
        }

        //当Gridview数据为空时显示的信息
        [Bindable(true), Category("Appearance"), DefaultValue("")]
        public string EmptyText
        {
            get { return emptytext; }
            set { emptytext = value; }
        }

        private string emptytext = string.Empty;
        /// <summary>
        /// 防止PostBack后Gridview不能显示
        /// </summary>
        /// <param name="gridview"></param>
        public void Reset()
        {
            //如果数据为空则重新构造Gridview
            if (this.Rows.Count == 1 && this.Rows[0].Cells[0].Text == EmptyText)
            {
                int columnCount = this.Columns.Count;
                this.Rows[0].Cells.Clear();
                this.Rows[0].Cells.Add(new TableCell());
                this.Rows[0].Cells[0].ColumnSpan = columnCount;
                this.Rows[0].Cells[0].Text = EmptyText;
                this.Rows[0].Cells[0].Style.Add("text-align", "center");
            }
        }

        /// <summary>
        /// 绑定数据到GridView，当表格数据为空时显示表头
        /// </summary>
        /// <param name="gridview"></param>
        /// <param name="table"></param>
        public void DataBind(DataTable table)
        {
            //记录为空重新构造Gridview
            if (table.Rows.Count == 0)
            {
                table = table.Clone();
                table.Rows.Add(table.NewRow());
                this.DataSource = table;
                this.DataBind();
                int columnCount = table.Columns.Count;
                this.Rows[0].Cells.Clear();
                this.Rows[0].Cells.Add(new TableCell());
                this.Rows[0].Cells[0].ColumnSpan = columnCount;
                this.Rows[0].Cells[0].Text = EmptyText;
                this.Rows[0].Cells[0].Style.Add("text-align", "center");
            }
            else
            {
                //数据不为空直接绑定
                this.DataSource = table;
                this.DataBind();
            }
            //重新绑定取消选择
            this.SelectedIndex = -1;
        }
    }
}
